package xyz.chaobei.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(CustomFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("CustomFilter-自定义初始化自己的过滤器 name={}", filterConfig.getFilterName());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        logger.info("CustomFilter-servlet request=" + servletRequest.getClass());
        logger.info("CustomFilter-servlet response=" + servletResponse.getClass());

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        logger.info("CustomFilter-servlet uri=" + request.getRequestURI());
        logger.info("CustomFilter-servlet URL=" + request.getRequestURL());

        // 如果是test 开头的请求，放行，其他进行拦截
        if (request.getRequestURI().startsWith("/test/")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        logger.info("CustomFilter-销毁");
    }
}
